package davel

import (
	"fmt"
	"net/http"
	//"syscall"
	"time"
)

func NewDavelApp() *DavelApp  {
	app := &DavelApp{}
	app.initConfig()
	app.initLog()
	return app
}

type DavelApp struct {
	server *http.Server
	DavelConfig *DavelConfig
	DavelLog *DavelLog
	DavelRedis *DavelRedis
}

func(this *DavelApp) Run()  {
	// 一个通知退出的chan
	//quit := make(chan os.Signal)
	//signal.Notify(quit)

	mux := http.NewServeMux()
	mux.Handle("/", &DavelHandler{davelApp: this})

	//server配置
	serverAddr := this.DavelConfig.getDataString("host","0.0.0.0") + ":" + this.DavelConfig.getDataString("port","2828")
	this.server = &http.Server{
		Addr:         serverAddr,
		WriteTimeout: time.Second * 5,
		Handler:      mux,
	}

	this.DavelLog.Write("Starting httpserver:" + serverAddr)
	err := this.server.ListenAndServe()
	if err != nil {
		// 正常退出
		if err == http.ErrServerClosed {
			fmt.Println("Server closed under request")
		} else {
			fmt.Println("Server closed unexpected" + err.Error())
		}
		defer this.Gc()
	}
}

//初始化配置
func(this *DavelApp) initConfig()  {
	if this.DavelConfig!=nil{
		return
	}
	this.DavelConfig = NewDavelConfig("config.json")
}

//初始化日志
func(this *DavelApp) initLog()  {
	if this.DavelLog!=nil{
		return
	}
	this.DavelLog = NewDavelLog()

	if this.DavelConfig==nil {
		fmt.Printf("请先初始化配置")
	}

	logDir := GetPwd() + FilePathSep() +  this.DavelConfig.getDataString("log.logDir","")
	isSendToFmt := this.DavelConfig.getDataBool("log.isSendToFmt",true)
	isSendToFile := this.DavelConfig.getDataBool("log.isSendToFile",true)
	isAppendTime := this.DavelConfig.getDataBool("log.isAppendTime",true)
	maxLines := this.DavelConfig.getDataInt64("log.maxLines",100000)

	this.DavelLog.Init(logDir,isSendToFmt,isSendToFile,isAppendTime,maxLines)
}

//初始化redis连接池
func(this *DavelApp) initRedisPool()  {
	if this.DavelRedis!=nil{
		return
	}

	if this.DavelConfig==nil {
		fmt.Printf("请先初始化配置")
	}

	if this.DavelConfig==nil {
		fmt.Printf("请先初始化配置")
	}

	config := DavelRedisConfig{
		Key: this.DavelConfig.getDataString("reids.Key","davelRedis"),
		Conn: this.DavelConfig.getDataString("reids.Conn","127.0.0.1:6379"),
		Password: this.DavelConfig.getDataString("reids.Password",""),
		DbNum: this.DavelConfig.getDataInt("reids.DbNum",0),
		MaxIdle: this.DavelConfig.getDataInt("reids.MaxIdle",256),
		IdleTimeout: this.DavelConfig.getDataInt("reids.IdleTimeout",120),
	}
	this.DavelRedis = newDavelRedis(config)
}

func(this *DavelApp) Gc()  {
	this.DavelLog.Gc()
}